package com.xiaowu.netmusic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaowu.netmusic.domain.po.History;
import com.xiaowu.netmusic.domain.po.Song;
import com.xiaowu.netmusic.domain.vo.HistoryVO;
import com.xiaowu.netmusic.mapper.HistoryMapper;
import com.xiaowu.netmusic.service.HistoryService;
import com.xiaowu.netmusic.service.SongService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {


    private final SongService songService;

    @Override
    public void recordPlay(Long userId, Long songId) {
        History history = new History();
        history.setUserId(userId);
        history.setSongId(songId);
        save(history);
    }

    @Override
    public IPage<HistoryVO> getUserHistory(Long userId, int page, int size) {
        Page<History> historyPage = new Page<>(page, size);
        IPage<History> pageResult = lambdaQuery()
                .eq(History::getUserId, userId)
                .orderByDesc(History::getPlayTime)
                .page(historyPage);

        List<HistoryVO> voList = pageResult.getRecords().stream().map(record -> {
            HistoryVO vo = new HistoryVO();
            vo.setPlayTime(record.getPlayTime());
            Song song = songService.getById(record.getSongId());
            if (song != null) {
                vo.setSongId(song.getId());
                vo.setTitle(song.getTitle());
                vo.setArtist(song.getArtist());
                vo.setCoverUrl(song.getCoverUrl());
            }
            return vo;
        }).collect(Collectors.toList());

        Page<HistoryVO> resultPage = new Page<>();
        resultPage.setCurrent(pageResult.getCurrent());
        resultPage.setTotal(pageResult.getTotal());
        resultPage.setSize(pageResult.getSize());
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    public void clearUserHistory(Long userId) {
        lambdaUpdate()
                .eq(History::getUserId, userId)
                .remove(); // 删除指定用户的所有历史记录
    }

        @Override
        public void deleteHistory(Long historyId, Long userId) {
            History history = getById(historyId);
            if (history == null) {
                throw new RuntimeException("历史记录不存在");
            }

            // 判断是否是历史记录的所有者
            if (!history.getUserId().equals(userId)) {
                throw new RuntimeException("只能删除自己的历史记录");
            }

            // 删除该历史记录
            removeById(historyId);
        }
    }

